import DefaultBackgroundImage from '../assets/bg.png';
import { DomUtils as DomUtilsMin } from './DomUtilsMin';

export class DomUtils extends DomUtilsMin {

    /**
     * 创建按钮的参数
     * @typedef {Object} CreateBtnConfig
     * @property {string} text 按钮文字，默认 "按钮"
     * @property {Element} parent 按钮父元素，指定按钮追加到那个元素下，默认body元素
     * @property {CSSStyleDeclaration} css 按钮css
     * @property {{ (btn: Element): void }} click 按钮点击事件
     */

    /**
     * 创建一个按钮，默认为fixed定位，悬浮在左侧
     * @param {CreateBtnConfig} config 自定义配置
     * @returns {Element} 创建的按钮
     */ 
    static createFixedButton({ text, parent, css, click }) {
        const btn = document.createElement('div');
        
        // 按钮文本
        btn.textContent = text || "按钮";

        // 按钮css
        const defaultBtnCss = {
            position: 'fixed',
            top: 0,
            left: 0,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '10px 8px',
            backgroundColor: '#007fff',
            letterSpacing: '2px',
            fontWeight: 'bold',
            fontSize: '15px',
            transition: '0.5s',
            color: '#fff',
            cursor: 'pointer',
            userSelect: 'none',
            borderTopRightRadius: '4px',
            borderBottomRightRadius: '4px',
        };
        css = css ? Object.assign(defaultBtnCss, css) : defaultBtnCss;
        Object.assign(btn.style, css);

        // 绑定click事件
        if (click) btn.addEventListener('click', () => click(btn));

        // 添加到页面
        parent = parent || document.body;
        parent.appendChild(btn);

        return btn;
    }

    /**
     * 设置背景图片
     * @param {string} selector 
     */
    static setBackground(selector) {
        let bgBox = document.body;
        if (selector) bgBox = document.body;
        Object.assign(bgBox.style, {
            'background-image':  `url(${DomUtils.base64ToBlobURL(DefaultBackgroundImage)})`,
            'background-position':  'center',
            'background-attachment':  'fixed',
            'background-repeat':  'no-repeat',
            'background-size':  'cover',
        });
    }
    
    /**
     * 将base64格式的图片转为Blob URL
     * @param {string} base64 base64格式的图片
     * @returns {string} Blob URL
     */
    static base64ToBlobURL(base64) {
        base64 = base64.replace(/^data:image\/(png|jpg|jpeg|webp);base64,/, '');
        let bstr = window.atob(base64),
            n = bstr.length,
            u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n);
        }
        return URL.createObjectURL(new Blob([u8arr], { type: base64 }));
    }
}